//
//  HomePageViewController.m
//  water
//
//  Created by chck999 on 2021/8/24.
//

#import "HomePageViewController.h"
#import "Masonry.h"
#import "NSString+labelSize.h"
#import "HCMainViewController.h"
#import "HcTextInputView.h"
#import <sqlite3.h>
#import "FMDatabase.h"
#import <sys/utsname.h>

#define kScreenSize [UIScreen mainScreen].bounds.size
@interface HomePageViewController ()<UITextFieldDelegate,HcTextInputViewDelegate>
// 提醒填写信心 label
@property (nonatomic, weak) UILabel *tipsLabel;
// 起床时间 label
@property (nonatomic, weak) UILabel *getUpTime;
// 设定起床时间
@property (nonatomic, weak) HcTextInputView *getUpTimeView;
// 体重Label
@property (nonatomic, weak) UILabel *weightLabel;
// 设定体重
@property (nonatomic, weak) HcTextInputView *weightView;
// 饮水量Label
@property (nonatomic, weak) UILabel *waterIntake;
// 设置饮水量
@property (nonatomic, weak) HcTextInputView *waterView;
// 数据库
@property (nonatomic, strong) FMDatabase *database;
// 数据库打开状态
@property (nonatomic, assign) BOOL success;

@property (nonatomic, copy) NSString *getupStr ;
@property (nonatomic, copy) NSString *weightStr;
@property (nonatomic, copy) NSString *waterIntakeStr;



@end

@implementation HomePageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"饮水计划信息";
    // 默认设置内的通知按钮式打开状态
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"swithState"];
    
    self.view.backgroundColor = [UIColor colorWithRed:36/255.0 green:46/255.0 blue:52/255.0 alpha:1.0];
    
    
    // 创建/读取本地数据库
    NSString *path            = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"datafmdb.sqlite"];
    FMDatabase *database      = [FMDatabase databaseWithPath:path];
    self.database             = database;
    BOOL success              =  [database open];
    self.success              =success;
    if (success) {
        BOOL successT1         =  [self.database executeUpdate:@"CREATE   TABLE IF NOT EXISTS t_firstSeting(id INTEGER PRIMARY KEY AUTOINCREMENT ,getupStr TEXT  , weightStr TEXT,waterIntakeStr TEXT);"];
        if (successT1) {
            // 插入一条初始化数据  INSERT INTO state(state) VALUES (5);
            BOOL successT1_1  =  [self.database executeUpdate:@"INSERT INTO t_firstSeting(getupStr,weightStr,waterIntakeStr) VALUES ('07:00','50','300');"];
            if (successT1_1) {
            }
        }
        BOOL successT2         =  [self.database executeUpdate:@"CREATE   TABLE IF NOT EXISTS t_mainSeting(id INTEGER PRIMARY KEY AUTOINCREMENT ,setButtonState INTEGER,progress TEXT,lastTime TEXT);"];
        if (successT2) {
            [self.database executeUpdate:@"DELETE FROM t_mainSeting ;"];
            // 插入一条初始化数据
            BOOL successT2_1  =  [self.database executeUpdate:@"INSERT INTO t_mainSeting(setButtonState,progress,lastTime) VALUES (0,'0','00:00')"];
            if (successT2_1) {
            }
        }
        BOOL successT3         =  [self.database executeUpdate:@"CREATE   TABLE IF NOT EXISTS t_record(id INTEGER PRIMARY KEY AUTOINCREMENT ,time TEXT,volume INTEGER, total INTEGER,fullTime TEXT);"];
        if (successT3) {
        }
    }
    //起床时间
    self.getupStr            = @"";
    //体重
    self.weightStr           = @"";
    //饮水量
    self.waterIntakeStr      = @"";
    // 查询定制的数据
    [self selectWithState:success];
    
#pragma mark 注册对键盘监听的通知
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

    UILabel * tipsLabel     = [[UILabel alloc] init];
    self.tipsLabel          = tipsLabel;
    [self.view addSubview:tipsLabel];
    
    tipsLabel.text          = @"请填写你的信息生成合理的饮水计划";
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    tipsLabel.textColor     = [UIColor colorWithRed:123/255.0 green:127/255.0 blue:131/255.0 alpha:1.0];
    if (mDevice < 8.0) {
        tipsLabel.font          = [UIFont systemFontOfSize:11.2];
    } else {
        tipsLabel.font          = [UIFont fontWithName:@"PingFangSC-Light" size:14];
    }

    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.top.offset(40);
            make.left.right.equalTo(self.view);
            make.height.equalTo(@16);
        } else {
            make.top.offset(45);
            make.left.right.equalTo(self.view);
            make.height.equalTo(@20);
        }
    }];
    
        // 你的起床时间
    UILabel * getUpTime     = [[UILabel alloc] init];
    self.getUpTime          = getUpTime;
    [self.view addSubview:getUpTime];
    
    getUpTime.textColor     = [UIColor whiteColor];
    getUpTime.text          = @"起床时间";
    getUpTime.textAlignment = NSTextAlignmentCenter;
    if (mDevice < 8.0) {
        getUpTime.font          = [UIFont systemFontOfSize:14.4];
    } else {
        getUpTime.font          = [UIFont fontWithName:@"PingFangSC-Thin" size:18];
    }

    [getUpTime mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.top.equalTo(tipsLabel.mas_bottom).offset(20);
            make.left.right.equalTo(self.view);
            make.height.equalTo(@20.5);
        } else {
            make.top.equalTo(tipsLabel.mas_bottom).offset(25.5);
            make.left.right.equalTo(self.view);
            make.height.equalTo(@25);
        }

    }];
    // 设定起床时间
    CGRect getupRect;
    if (mDevice < 8.0) {
        
        getupRect = CGRectMake(0, 0, 117.5, 40.5);
    } else {

        getupRect = CGRectMake(0, 0, 147, 50);
        
    }
    
    HcTextInputView * getUpTimeView = [[HcTextInputView alloc] initWithFrame:getupRect withType:@"time1"];
    
    getUpTimeView.delegate      = self;
    [self setDataUseSelectResultWith:getUpTimeView andResultString:self.getupStr andString:@"07:00"];
    
    self.getUpTimeView   = getUpTimeView;
    [self.view addSubview:getUpTimeView];
    
    [getUpTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.top.equalTo(getUpTime.mas_bottom).offset(4.5);
        } else {
            make.top.equalTo(getUpTime.mas_bottom).offset(6);
        }
        make.centerX.equalTo(self.view);
    }];
    // 你的体重
    UILabel * weightLabel     = [[UILabel alloc] init];
    self.weightLabel          = weightLabel;
    weightLabel.text          = @"体重";
    weightLabel.textAlignment = NSTextAlignmentCenter;
    weightLabel.textColor     = [UIColor whiteColor];
    if (mDevice < 8.0) {
        weightLabel.font          = [UIFont systemFontOfSize:14.4];
    } else {
        weightLabel.font          = [UIFont fontWithName:@"PingFangSC-Thin" size:18];
    }

    [self.view addSubview:weightLabel];
    
    [weightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.height.equalTo(@20.5);
            make.width.equalTo(@101);
            make.left.equalTo(@((kScreenSize.width - 101) /2));
            make.top.equalTo(getUpTimeView.mas_bottom).offset(4.5);
        } else {
            make.height.equalTo(@25);
            make.width.equalTo(@126);
            make.left.equalTo(@((kScreenSize.width - 126) /2));
            make.top.equalTo(getUpTimeView.mas_bottom).offset(6);
        }

    }];
    
    // 体重
    CGRect weightRect;
    if (mDevice < 8.0) {
        weightRect = CGRectMake(0, 0, 117.5, 40.5);
    } else {
        weightRect = CGRectMake(0, 0, 147, 50);
    }
    HcTextInputView * weightView   = [[HcTextInputView alloc] initWithFrame:weightRect withType:@""];
    self.weightView            = weightView;
    // 通过查询数据库结果设定体重
    [self setDataUseSelectResultWith:weightView andResultString:self.weightStr andString:@"50"];
    weightView.delegate        = self;
    
    [self.view addSubview:weightView];
    
    [weightView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.top.equalTo(weightLabel.mas_bottom).offset(4);
            make.centerX.equalTo(self.view);
            make.left.right.equalTo(getUpTimeView);
        } else {
            make.top.equalTo(weightLabel.mas_bottom).offset(6);
            make.centerX.equalTo(self.view);
            make.left.right.equalTo(getUpTimeView);
        }
        
    }];
    // 每次饮水量
    UILabel * waterIntake     = [[UILabel alloc] init];
    self.waterIntake          = waterIntake;
    [self.view addSubview:waterIntake];
    waterIntake.text          = @"每次饮水量";
    waterIntake.textAlignment = NSTextAlignmentCenter;
    waterIntake.textColor     = [UIColor whiteColor];
    if (mDevice < 8.0) {
        waterIntake.font          = [UIFont systemFontOfSize:14.4];
    } else {
        waterIntake.font          = [UIFont fontWithName:@"PingFangSC-Thin" size:18];
    }
    [waterIntake mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.height.equalTo(@20.5);
            make.width.equalTo(@101);
            make.left.equalTo(@((kScreenSize.width - 101) /2));
            make.top.equalTo(weightView.mas_bottom).offset(4.5);
        } else {
            make.height.equalTo(@25);
            make.width.equalTo(@108);
            make.left.equalTo(@((kScreenSize.width - 108) /2));
            make.top.equalTo(weightView.mas_bottom).offset(6);
        }
    }];
    
    
    // 饮水量
    CGRect waterRect;
    if (mDevice < 8.0) {
        waterRect = CGRectMake(0, 0, 115, 40.5);
    } else {
        waterRect = CGRectMake(0, 0, 147, 50);
        
    }
    HcTextInputView * waterView   = [[HcTextInputView alloc] initWithFrame:waterRect withType:@"special"];
    self.waterView            = waterView;
    waterView.delegate        = self;
    [self setDataUseSelectResultWith:waterView andResultString:self.waterIntakeStr andString:@"300"];
    
    [self.view addSubview:waterView];
    
    [waterView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (mDevice < 8.0) {
            make.top.equalTo(waterIntake.mas_bottom).offset(4.5);
        } else {
            make.top.equalTo(waterIntake.mas_bottom).offset(6);
        }
        make.centerX.equalTo(self.view);
        make.left.right.equalTo(getUpTimeView);
    }];
    
    
    // 确定
    UIButton * confirm      = [[UIButton alloc] init];
    [self.view addSubview:confirm];
    
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    confirm.backgroundColor = [UIColor whiteColor];
    // 设置圆角
    [confirm.layer setMasksToBounds:YES];

    if (mDevice < 8.0) {
        [confirm.layer setCornerRadius:20];
        confirm.titleLabel.font = [UIFont systemFontOfSize:14.4];
    } else {
        [confirm.layer setCornerRadius:25];
        confirm.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:18];
        
    }
    [confirm addTarget:self action:@selector(didClickConfirmButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [confirm mas_makeConstraints:^(MASConstraintMaker *make) {
       
        if (mDevice < 8.0) {
            make.bottom.offset(-20);
            make.size.mas_equalTo(CGSizeMake(140.4, 39.3));
        } else {
            make.bottom.offset(-20);
            make.size.mas_equalTo(CGSizeMake(175.5, 49));
        }
        make.centerX.equalTo(self.view.mas_centerX);
    }];

}

#pragma mark UITextFeild代理方法

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES] ;
    
    return YES;
}

#pragma mark 点击确定
- (void)didClickConfirmButton:(UIButton *)btn {
    
    
#pragma mark 点击按钮之后判断对应数据是否输入,然后将数据保存到本地
    
    
    if (![self.getUpTimeView.inputfeild.text  isEqual: @""] && ![self.weightView.inputfeild.text isEqualToString:@""] && ![self.waterView.inputfeild.text isEqualToString:@""]) {
        
        
        // 保存数据
        [self insertDataWith:self.getUpTimeView.inputfeild.text andWeightStr:self.weightView.inputfeild.text andWaterIntakeStr:self.waterView.inputfeild.text];
        
        // 关闭连接
        [self.database close];
        
        // 跳转到主界面
        HCMainViewController * mainVC = [[HCMainViewController alloc] init];
        mainVC.username = self.username;
        [self presentViewController:mainVC animated:YES completion:^{
            
        }];
        
    }
}

#pragma mark LSInputView 代理方法
- (void)inputViewDelegate {

    [self.view endEditing:YES];
}


#pragma mark 监听到键盘frame的变化的通知
- (void)keyboardWillChangeFrame:(NSNotification *)note {
    
    if (!self.waterView.inputfeild.isEditing) {
        return;
    }else {
    
        CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        CGFloat transformY   = keyboardFrame.origin.y - self.view.bounds.size.height;
        self.view.transform  = CGAffineTransformMakeTranslation(0, transformY);
    }
    
}

#pragma mark  封装查询过程
- (void)selectWithState:(BOOL)success {
    if (success) {
        NSString *sql       = @"SELECT  getupStr,weightStr,waterIntakeStr FROM t_firstSeting ;";
        FMResultSet *result = [self.database executeQuery:sql];
        while ([result next]) {
            
            //起床时间 TEXT
            self.getupStr   =   [result stringForColumnIndex:0];
            //体重
            self.weightStr  =  [result stringForColumnIndex:1];
            //饮水量
            self.waterIntakeStr =  [result stringForColumnIndex:2];
        }
    }
}

#pragma mark  封装插入过程
- (void)insertDataWith:(NSString *)getupStr andWeightStr:(NSString *)weightStr andWaterIntakeStr:(NSString *)waterIntakeStr {
#pragma mark  插入前删除前面插入的数据.
//
    NSString * tmpSql = [NSString stringWithFormat:@"DELETE FROM t_firstSeting ;"];

    BOOL tmpSuccess =  [self.database executeUpdate:tmpSql];
    if (tmpSuccess) {
    }

//
//////////////////////////////////////////////////////////////////////////////////////////////////////
    
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_firstSeting (getupStr,weightStr,waterIntakeStr) VALUES ('%@','%@','%@')",getupStr,weightStr,waterIntakeStr];
    BOOL success =  [self.database executeUpdate:sql];
    if (success) {
    }
    
}

#pragma mark 通过查询结果设定控件数据
- (void)setDataUseSelectResultWith:(HcTextInputView *)view andResultString:(NSString *)resultString andString:(NSString *)preString {
    if ([resultString isEqualToString:@""]) {
        view.inputfeild.text = preString;
    }else {
        view.inputfeild.text = resultString;
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
}

@end
